home *** CD-ROM | disk | FTP | other *** search
- Path: vixen.cso.uiuc.edu!usenet
- From: homer@uiuc.edu
- Newsgroups: comp.lang.c++
- Subject: Re: resetting a character array
- Date: 9 Feb 1996 03:51:09 GMT
- Organization: University of Illinois at Urbana
- Message-ID: <4fegbd$1o3@vixen.cso.uiuc.edu>
- References: <4fbt20$4o3@cloner3.netcom.com>
- Reply-To: n-dade@uiuc.edu
- NNTP-Posting-Host: homer.apr.uiuc.edu
- X-Newsreader: IBM NewsReader/2 v1.2
-
- In <4fbt20$4o3@cloner3.netcom.com>, Manuel Hernandez <ManuelHe@ix.netcom.com> writes:
- >This must be a total beginners question. How do you reset
- >a character array so you can enter a string into a variable
- >over and over again? This is what I have so far.
-
- istream::getline() overwrites the previous contents of the array, so there is no
- need to "reset" the array to empty. (If you want the array to represent the
- empty string then you put the 0 character in the first element of the array:
- name[0] = 0;
- but you don't have to for getline().)
-
- >void main()
- >{
- > char name[20];
- > char answer;
- >
- > do
- > {
- > cout << "Enter a name" << endl;
- > cin.getline(name,20);
- >
- > cout << name << " is a nice name. Enter another? " << endl;
- > cin >> answer;
- >
- > }
- > while (answer == 'y');
- > return;
- >}
-
- I copy/pasted/compiled and ran this little program and I think I see the
- problem you are dealing with: It runs like this:
-
- Enter a name
- user enters "Nicolas" and presses return.
- Nicolas
- Nicolas is a nice name. Enter another?
- user enters "y" and presses return
- y
- Enter a name
- is a nice name. Enter another?
- user enters "n" and presses return
- n
-
- What has happened is that cin still contains the "end of line" character that
- the user entered after the "y". This is because when you read from cin you
- only read one single "y". Then the next time you read from cin you use
- getline() which reads until it finds an "end of line" character. It finds that
- immediately, and you don't get the name you wanted.
-
- The solution is to read the entire response to the "Enter another?" question,
- including the end-of-line, before reading the next name from cin. I'd
- suggest using getline() to read the "y" as well. Here are the 3 lines that
- change:
-
- char answer[10]; // <--- changed answer to be an array as well
- ..
- cin.getline(answer, 10); // <--- read the entire response
- ..
- while (answer[0] == 'y'); // <--- check the 1st letter of the response is "y"
-
-
-
-